package com.example.tomatotodo.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

import com.example.tomatotodo.api.ApiClient;
import com.example.tomatotodo.api.ApiService;
import com.example.tomatotodo.model.Result;
import com.example.tomatotodo.model.TodoRecordSyncDTO;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RecordUploadManager {
    private static final String TAG = "RecordUploadManager";
    private Context context;

    public RecordUploadManager(Context context) {
        this.context = context;
    }

    /**
     * 获取本地存储的专注记录
     *
     * @return 本地专注记录列表
     */
    private List<TodoRecordSyncDTO> getLocalRecords() {
        Log.d(TAG, "getLocalRecords: 获取本地专注记录列表");
        SharedPreferences prefs = context.getSharedPreferences("focus_records_prefs", Context.MODE_PRIVATE);
        String recordsJson = prefs.getString("focus_records", "[]");

        Gson gson = RecordUtil.getGsonInstance(); // 使用RecordUtil中的Gson实例来正确处理LocalDateTime
        Type listType = new TypeToken<List<TodoRecordSyncDTO>>() {
        }.getType();
        List<TodoRecordSyncDTO> records = gson.fromJson(recordsJson, listType);

        if (records == null) {
            records = new ArrayList<>();
        }

        Log.d(TAG, "getLocalRecords: 本地专注记录数量: " + records.size());
        return records;
    }

    /**
     * 上传记录到云端
     */
    public void uploadRecords() {
        Log.d(TAG, "开始上传本地记录到云端");

        // 检查用户登录状态
        if (!TokenManager.isLoggedIn(context)) {
            Log.w(TAG, "用户未登录，无法上传记录");
            Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取本地记录
        List<TodoRecordSyncDTO> localRecords = getLocalRecords();
        if (localRecords.isEmpty()) {
            Log.w(TAG, "本地没有专注记录");
            Toast.makeText(context, "本地没有专注记录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 调用API上传记录
        String token = TokenManager.getToken(context);
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<Result<Void>> call = apiService.uploadRecords("Bearer " + token, localRecords);

        call.enqueue(new Callback<Result<Void>>() {
            @Override
            public void onResponse(Call<Result<Void>> call, Response<Result<Void>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Result<Void> result = response.body();
                    Log.d(TAG, "上传记录响应成功，状态码: " + result.getCode());
                    if (result.getCode() == 200) {
                        Log.d(TAG, "上传记录成功");
                        Toast.makeText(context, "上传成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Log.w(TAG, "上传记录失败，错误码: " + result.getCode() + "，信息: " + result.getMessage());
                        Toast.makeText(context, "上传失败，请检查网络 ", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.e(TAG, "上传记录响应失败，响应码: " + response.code());
                    Toast.makeText(context, "上传失败，响应码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result<Void>> call, Throwable t) {
                Log.e(TAG, "上传记录网络请求失败: " + t.getMessage(), t);
                Toast.makeText(context, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
